package com.y.mytest.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName: TestCOntroller
 * @author: 叶子豪
 * @create: 2020-07-30 13:58
 */
@Controller
@RequestMapping("/event")
public class TestController {
    @RequestMapping("/events")
    @ResponseBody
    public Object TestCon(@RequestBody(required = false) String jsonObject, HttpServletRequest request) {
        System.out.println(request.getHeader("X-Auth-Token"));
        System.out.println(jsonObject);
        return jsonObject;
    }

    @RequestMapping("/events2")
    @ResponseBody
    public Object TestCon2(String jsonObject, HttpServletRequest request) {
        System.out.println(jsonObject);
        System.out.println(request.getParameter("token"));
        System.out.println(request.getParameter("msg"));
        System.out.println(request.getParameter("qwe"));
        System.out.println(request.getParameter("2"));
        System.out.println(request.getParameter("deviceKey"));
        return jsonObject;
    }

    @RequestMapping("/testFile")
    @ResponseBody
    public Object TestFile(MultipartFile multipartFile) {
        try {
            byte[] bytes = multipartFile.getBytes();

            final int fileSize = bytes.length;
            int bufferSize = 10 * 1024 * 1024;
            int startPosition = 0; //子文件开始位置
            int endPosition = bufferSize;//子文件结束位置
            int fileCount = fileSize % bufferSize == 0 ? fileSize / bufferSize : fileSize / bufferSize + 1;

            List<byte[]> byteList = new ArrayList<>();
            List<String> mdList = new ArrayList<>();

            for (int i = 0; i < fileCount; i++) {

                if (i + 1 == fileCount) {
                    endPosition = fileSize;
                }
                byte[] copy = Arrays.copyOfRange(bytes, startPosition, endPosition);

                byteList.add(copy);
                mdList.add(DigestUtils.md5Hex(copy));
                System.out.println(DigestUtils.md5Hex(copy));

                startPosition = endPosition;
                endPosition = endPosition + bufferSize;
            }

            System.out.println(byteList);
            System.out.println(mdList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    }
}
